package com.example.spletnatrgovina;

import java.io.InputStream;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import com.example.spletnatrgovina.model.Produkt;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ProduktActivity extends ListActivity {
	
    public static final String URL_PREFIX = "http://10.0.2.2/spletna/";
	public static final String ALL_PRODUKTS = URL_PREFIX+"rest/format/json/method/seznam";
    
	private ListView listView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		new GetProduktsAsync(getApplicationContext()).execute();
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		//String url = (String) ((CustomList) getListAdapter()).getUrl(position);
		//Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(URL_PREFIX+url));
		//startActivity(browserIntent);
		
		Intent i = new Intent(this, ProduktDetailActivity.class);
		i.putExtra("id", ((CustomList) getListAdapter()).getProdukt(position).getId());
		startActivity(i);
	
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.produkt, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	
	private class GetProduktsAsync extends AsyncTask<Void, Void, Tuple> {
		private final Context context;
	
		public GetProduktsAsync(Context c) {
			context = c;
		}
	
		@Override
		protected Tuple doInBackground(Void... params) {
			try {
				HttpClient client = new DefaultHttpClient();
				HttpGet request = new HttpGet(ALL_PRODUKTS);
				HttpResponse response = client.execute(request);
				HttpEntity httpEntity = response.getEntity();
	
				JSONObject json = new JSONObject(EntityUtils.toString(httpEntity));
	
				if (json.getString("success").equals("true")) {
					JSONArray items = json.getJSONArray("seznam");
					Produkt[] produkts = new Produkt[items.length()];
	
					for (int i = 0; i < items.length(); i++) {
	
						JSONObject o = items.getJSONObject(i);
						produkts[i] = new Produkt(o.getInt("id"), o.getString("ime"),
								o.getDouble("cena"), o.getInt("zaloga"), o.getString("base_image"),
								o.getString("thumbnail"), o.getString("url"));
					}
	
					
					
					return new Tuple(getImages(produkts), produkts);
				}
	
			} catch (Exception e) {
				e.printStackTrace();
			}
	
			return null;
		}
	
		@Override
		protected void onPostExecute(Tuple tuple) {
			if (tuple.getProdukts() == null) {
				Toast.makeText(context, "An error occured.", Toast.LENGTH_LONG).show();
			} else {
				CustomList adapter = new CustomList(ProduktActivity.this,
						toStringArray(tuple.getProdukts()), tuple.getImages(), tuple.getProdukts());
				setListAdapter(adapter);
			}
		}
		
		protected String[] toStringArray(Produkt[] produkts) {
			String[] prods = new String[produkts.length];
			int i = 0;
			for (Produkt p : produkts) {
				prods[i] = p.toString();
				i++;
			}
			return prods;
		}
		
		protected Bitmap[] getImages(Produkt[] produkts) {
			Bitmap[] bitmaps = new Bitmap[produkts.length];
			int i = 0;
			for (Produkt p : produkts) {
				
				try {
			        URL url = new URL(URL_PREFIX+p.getThumbnail());
			        
			        
			        HttpGet httpRequest = null;
			        httpRequest = new HttpGet(url.toURI());
			        HttpClient httpclient = new DefaultHttpClient();
			        Log.i("image url", URL_PREFIX+p.getThumbnail());

			        HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);

			        HttpEntity entity = response.getEntity();

			        BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
			        InputStream input = b_entity.getContent();
			        Bitmap bitmap = BitmapFactory.decodeStream(input);

			        bitmaps[i] = bitmap;

			    } catch (Exception ex) {
                    Log.e("image url", "msg: "+ex.getMessage());
			    }
				
				i++;
			}
			return bitmaps;
		}
	}
	
	private class Tuple {
		private Bitmap[] images = null;
		private Produkt[] produkts = null;
		
		public Tuple(Bitmap[] images, Produkt[] produkts) {
			this.images = images;
			this.produkts = produkts;
		}
		
		public Bitmap[] getImages() {
			return this.images;
		}
		
		public Produkt[] getProdukts() {
			return this.produkts;
		}
	}
	
	public class CustomList extends ArrayAdapter<String>{
		private final Activity context;
		private final String[] web;
		private final Bitmap[] images;
		private final Produkt[] produkts;
		public CustomList(Activity context,String[] web, Bitmap[] images, Produkt[] produkts) {
			super(context, R.layout.list_single, web);
			this.context = context;
			this.web = web;
			this.images = images;
			this.produkts = produkts;
		}
		@Override
		public View getView(int position, View view, ViewGroup parent) {
			LayoutInflater inflater = context.getLayoutInflater();
			View rowView= inflater.inflate(R.layout.list_single, null, true);
			TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
			ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
			txtTitle.setText(web[position]);
			imageView.setImageBitmap(images[position]);
			return rowView;
		}
		
		public Produkt getProdukt(int position) {
			return this.produkts[position];
		}
		
		public String getUrl(int position) {
			return produkts[position].getUrl();
		}
	}
}
